package com.train.synchronous;

public class TicketsSales implements Runnable{
    //票数量
    private Integer ticketsNums;
    public TicketsSales(Integer ticketsNums ){
        this.ticketsNums = ticketsNums;
    }
    @Override
    public void run() {
        try {
          //buyTicket();
            buyTicket2();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 第一种方法，对方法加同步锁
     * */
    private synchronized void buyTicket() throws InterruptedException {
        if (ticketsNums >= 1){
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName+"购买第："+ticketsNums+" 张票");
            ticketsNums --;
            //买完一张表，将CPU执行权礼让给其他线程，但自身还是会进入下一次CPU的抢夺
            Thread.currentThread().yield();
            Thread.currentThread().sleep(100);
        }
    }
    /**
     * 第二种方法：同步锁代码块：对资源加锁
     * */
    private void buyTicket2() throws InterruptedException {
        synchronized(ticketsNums){
            if (ticketsNums >= 1){
                String threadName = Thread.currentThread().getName();
                System.out.println(threadName+"购买第："+ticketsNums+" 张票");
                ticketsNums --;
                //买完一张表，将CPU执行权礼让给其他线程，但自身还是会进入下一次CPU的抢夺
                Thread.currentThread().yield();
                Thread.currentThread().sleep(100);
            }
        }
    }
}
